package com.l024.easyandroidlib.http.request;

import java.io.File;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @Author: Cat
 * @CreateTime: 2022-07-29  10:44
 * @Description: TODO
 * @Version: 1.0
 */
public class HttpRequest {
    /**
     * 创建json的RequestBody
     * @param json
     */
    public static RequestBody createJsonRequestBody(String json){
        MediaType mediaType=MediaType.Companion.parse("application/json;charset=utf-8");
        return RequestBody.Companion.create(json,mediaType);
    }

    /**
     * 文件上传的body
     * @param fileKey:后端接收文件的name字段
     */
    public static MultipartBody createMultipartBody(Map<String,Object> map,String fileKey,File file){
        MultipartBody.Builder builder = new MultipartBody.Builder();
        if(map!=null){
            for(String key:map.keySet()){
                builder.addFormDataPart(key,map.get(key)+"");
            }
        }
        MediaType mediaType=MediaType.Companion.parse("image/jpg");
        if(file!=null){
            RequestBody requestBody = RequestBody.Companion.create(mediaType,file);
            builder.addFormDataPart(fileKey, file.getName(), requestBody);
        }
        builder.setType(MultipartBody.FORM);
        return builder.build();
    }

    /**
     * 文件上传的body
     * @param files:后端接收文件的name字段
     */
    public static MultipartBody createMultipartBody(Map<String,Object> map, String fileKey, List<File> files){
        MultipartBody.Builder builder = new MultipartBody.Builder();
        if(map!=null){
            for(String key:map.keySet()){
                builder.addFormDataPart(key,map.get(key)+"");
            }
        }
        MediaType mediaType=MediaType.Companion.parse("image/jpg");
        if(files!=null&&files.size()>0){
            for(File f:files){
                if(f!=null){
                    RequestBody requestBody = RequestBody.Companion.create(mediaType,f);
                    builder.addFormDataPart(fileKey, f.getName(), requestBody);
                }
            }
        }
        builder.setType(MultipartBody.FORM);
        return builder.build();
    }
}
